#include "head.h"

void* thread_main(void* tmp){

    Send* s = (Send*)tmp;
    pthread_mutex_lock(&s->lock);

    
    char ip[100];
    bzero(ip, sizeof(ip));
    getparameter("ip", ip);

    char port[100];
    bzero(port, sizeof(port));
    getparameter("port", port);

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);

    connect(socket_fd, (struct sockaddr*)&sockaddr, sizeof(sockaddr));
    //printf("sock: %d\n", socket_fd);

    char a = '#';
    if(s->command_type){
        a = '%';
    }
    send(socket_fd, &a, sizeof(char), MSG_WAITALL);
//printf("a: %c\n", a);
    send(socket_fd, &a, sizeof(char), MSG_WAITALL);
//printf("a: %c\n", a);
    char token[1024] = {0};
    memset(token, 0, sizeof(token));
    strcpy(token, s->token);
    //if(s->command_type == 0){
        off_t len = strlen(token);
        send(socket_fd, &len, sizeof(off_t), MSG_NOSIGNAL);
        send(socket_fd, token, len, MSG_NOSIGNAL);
        //printf("\n\n\ntoken:%s\n", token);

        char buf[4096] = {0};
        memset(token, 0, sizeof(token));
        snprintf(buf,sizeof(buf),"%s&%s&",
                 s->cut_buf, s->path);
        //len = strlen(buf);
        //send(socket_fd, &len, sizeof(off_t), MSG_NOSIGNAL);
        //send(socket_fd, buf, len, MSG_NOSIGNAL);
//printf("buf: %s\n", buf);

    //}

    user_t* user = s->user;
    char arg[512] = {0};
    memset(arg, 0, sizeof(arg));
    strcpy(arg, s->argx);

    //printf("arg: %s", arg);
    off_t token_len = 0;
    char token_tmp[1024] = {0};
    memset(token_tmp, 0, sizeof(token));
    int ret_recv = recv(socket_fd, &token_len, sizeof(token_len), MSG_WAITALL);
    //printf("len: %ld\n", token_len);
    if(ret_recv == 0){
        return 0;
    }
    ret_recv = recv(socket_fd, token_tmp, token_len, MSG_WAITALL);
    if(ret_recv == 0){
        return 0;
    }   
//printf("token_tmp: %s\n", token_tmp);

    
    if(s->command_type){
        get_client(socket_fd, token_tmp, user,arg);

    }else{
        snd_cmd(socket_fd,token_tmp,user,arg);
    }
    pthread_mutex_unlock(&s->lock);
    printf("%s: %s -> ", user->user_name, user->path);
    fflush(stdout);
    pthread_exit(NULL);

    return 0;
}
